var express = require('express');
var router = express.Router();
var db = require('../model/db.js');
var async = require('async');

/* GET articles listing. */
router.get('/', function(req, res, next) {
    var sql='select * from articles;';
    db.query(sql,function(err,rows){
        res.send(rows);
    });
});
router.post('/', function(req, res, next) {
    var data = req.body;
    var sql='insert into articles(title,cat_name) values(?,?);';
    db.query(sql,[data.title,data.cat_name],function(err,rows){
        if(!err){
            data.id=rows.insertId;
            res.send(data);
        }
    });
});
router.delete('/:id',function(req,res,next){
    var sql='delete from articles where id=?;';
    db.query(sql,[req.params.id],function(err,rows){
        if(!err){
            res.send({});
        }
    })
});
router.put('/:id',function(req,res,next){
    var data=req.body;
    console.log(data);
    var sql='update articles set title=?,cat_name=? where id=?;';
    db.query(sql,[data.title,data.cat_name,data.id],function(err,rows){
        if(!err){
            res.send(data);
        }
    })
});

module.exports = router;
